package a12_图论;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * <p>
 * a06_岛屿数量广搜版复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/4/7
 */
public class a06_岛屿数量广搜版复习2 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int rows = scanner.nextInt();
        int cols = scanner.nextInt();

        int[][] grid = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                grid[i][j] = scanner.nextInt();
            }
        }

        int result = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(grid[i][j] == 1){
                    result++;
                    //如果是岛屿，将本节点以及临近的都设置为海洋
                    grid[i][j] = 0;
                    bfs(grid,i,j);
                }
            }
        }
        System.out.println(result);

    }

    public static final int[][] dirs = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};
    private static void bfs(int[][] grid, int x, int y) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{x,y});

        while (!queue.isEmpty()) {
            int[] poll = queue.poll();
            for (int[] dir : dirs) {
                int nextX = poll[0] + dir[0];
                int nextY = poll[1] + dir[1];
                if(nextX >= 0 && nextX < grid.length && nextY >= 0 && nextY < grid[0].length){
                    if(grid[nextX][nextY] == 1){
                        grid[nextX][nextY] = 0;
                        queue.add(new int[]{nextX,nextY});
                    }
                }
            }
        }
    }
}
